package com.ruoyi.training.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.examination.domain.PaperConfig;
import com.ruoyi.examination.mapper.PaperConfigMapper;
import com.ruoyi.examination.service.IPaperConfigService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.training.domain.ClassStudent;
import com.ruoyi.training.dto.ExamScheduleDto;
import com.ruoyi.training.mapper.ClassStudentMapper;
import com.ruoyi.training.service.IExaminationControlService;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.mapper.ExamScheduleMapper;
import com.ruoyi.training.domain.ExamSchedule;
import com.ruoyi.training.service.IExamScheduleService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 考试安排Service业务层处理
 *
 * @author lqx
 * @date 2025-10-30
 */
@Service
public class ExamScheduleServiceImpl implements IExamScheduleService {

    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    @Autowired
    private ExamScheduleMapper examScheduleMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private PaperConfigMapper paperConfigMapper;

    @Autowired
    private ClassStudentMapper classStudentMapper;

    @Autowired
    private IExaminationControlService examinationControlService;

    /**
     * 查询考试安排
     *
     * @param examScheduleId 考试安排主键
     * @return 考试安排
     */
    @Override
    public ExamSchedule selectExamScheduleByExamScheduleId(String examScheduleId) {
        return examScheduleMapper.selectExamScheduleByExamScheduleId(examScheduleId);
    }

    /**
     * 查询考试安排列表
     *
     * @param examSchedule 考试安排
     * @return 考试安排
     */
    @Override
    public List<ExamSchedule> selectExamScheduleList(ExamSchedule examSchedule) {
        return examScheduleMapper.selectExamScheduleList(examSchedule);
    }

    /**
     * 新增考试安排
     *
     * @param examSchedule 考试安排
     * @return 结果
     */
    @Override
    public int insertExamSchedule(ExamSchedule examSchedule) {
        examSchedule.setExamScheduleId(String.valueOf(snowflake.nextId()));
        examSchedule.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        examSchedule.setCreateTime(DateUtils.getNowDate());
        int result = examScheduleMapper.insertExamSchedule(examSchedule);
        return result;
    }

    /**
     * 修改考试安排
     *
     * @param examSchedule 考试安排
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateExamSchedule(ExamSchedule examSchedule) {
        examSchedule.setUpdateTime(DateUtils.getNowDate());
        examSchedule.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        //通过考试安排生成试卷
        //判断新增试卷数量是否为空
        if (examSchedule.getCounts() != null){
            ExamSchedule examSchedule1 = new ExamSchedule();
            BeanUtils.copyProperties(examSchedule,examSchedule1);
            //不为空，调用生成试卷方法
            int examNum = examinationControlService.generatedPaper(examSchedule1);
            examSchedule.setExamNum(examNum);
        }
        int result = examScheduleMapper.updateExamSchedule(examSchedule);
        //修改班级中该项目的学员对应的考试状态,同时设置考试安排id
        //1.获取当前考试的项目id
        String paperConfigId = examSchedule.getPaperConfigId();
        //获取班级id
        String trainingClassId = examSchedule.getTrainingClassId();
        //获取考试对应的项目id
        PaperConfig paperConfig = classStudentMapper.selectPaperConfigByPaperConfigId(paperConfigId);
        String trainingProjectId = paperConfig.getTrainingProjectId();
        //2.通过项目id和班级id去班级学员表中匹配对应的学员id String[]
        List<String> studentIds = classStudentMapper.selectStudentIdsByClassIdAndProjectId(trainingClassId, trainingProjectId);
        //3.通过项目id和班级id去班级学员表中匹配对应的项目id String[]
        List<String> registrationIds = classStudentMapper.selectRegistrationIdsByClassIdAndProjectId(trainingClassId, trainingProjectId);
        //4.通过数据修改对应的考试安排状态
        classStudentMapper.batchUpdateExamStatus(trainingClassId,registrationIds,"1",examSchedule.getExamScheduleId());
        return result;
    }

    /**
     * 批量删除考试安排
     *
     * @param examScheduleIds 需要删除的考试安排主键
     * @return 结果
     */
    @Override
    public int deleteExamScheduleByExamScheduleIds(String[] examScheduleIds) {
        return examScheduleMapper.deleteExamScheduleByExamScheduleIds(examScheduleIds);
    }

    /**
     * 删除考试安排信息
     *
     * @param examScheduleId 考试安排主键
     * @return 结果
     */
    @Override
    public int deleteExamScheduleByExamScheduleId(String examScheduleId) {
        return examScheduleMapper.deleteExamScheduleByExamScheduleId(examScheduleId);
    }

    /**
     * 通过班级id获取考试安排详细信息
     * lqx
     */
    @Override
    public List<ExamScheduleDto> selectExamScheduleByClassId(String trainingClassId) {
        List<ExamSchedule> examScheduleList = examScheduleMapper.selectExamScheduleByClassId(trainingClassId);
        List<ExamScheduleDto> examScheduleDtoList = new ArrayList<>();
        if (examScheduleList != null && !"".equals(examScheduleList)) {
            for (ExamSchedule examSchedule : examScheduleList) {
                ExamScheduleDto examScheduleDto = new ExamScheduleDto();
                //复制
                BeanUtils.copyProperties(examSchedule, examScheduleDto);
                //赋值试卷信息名字
                if (examScheduleDto.getPaperConfigId() != null && !"".equals(examScheduleDto.getPaperConfigId())) {
                    PaperConfig paperConfig = examScheduleMapper.selectPaperConfigNameByPaperConfigId(examScheduleDto.getPaperConfigId());
                    examScheduleDto.setPaperConfigName(paperConfig.getPaperConfigName());
                }
                //赋值监考老师名字
                if (examScheduleDto.getInvigilatorId() != null && !"".equals(examScheduleDto.getInvigilatorId())) {
                    R<SysUser> userInfoById = remoteUserService.getUserInfoById(Long.valueOf(examScheduleDto.getInvigilatorId()), SecurityConstants.INNER);
                    examScheduleDto.setTeacherName(userInfoById.getData().getNickName());
                }
                //赋值考试途径-（0-手机、1-电脑）多选则字符串拼接(0,1)
                if (examScheduleDto.getExamPathway() != null && !"".equals(examScheduleDto.getExamPathway())) {
                    if ("0".equals(examScheduleDto.getExamPathway())) {
                        examScheduleDto.setExamPathwayName("手机");
                    }
                    if ("1".equals(examScheduleDto.getExamPathway())) {
                        examScheduleDto.setExamPathwayName("电脑");
                    }
                    if ("0,1".equals(examScheduleDto.getExamPathway())) {
                        examScheduleDto.setExamPathwayName("手机;电脑");
                    }
                }
                examScheduleDtoList.add(examScheduleDto);
            }
        }
        return examScheduleDtoList;
    }
}
